using SanJ.FreeCare.Abp.Chat;
using SanJ.FreeCare.Chat;
using SanJ.FreeCare.Features;
using System;
using Volo.Abp;
using Volo.Abp.Domain.Services;
using Volo.Abp.Features;

namespace SanJ.FreeCare.Chat
{
    public class ChatFeatureChecker : DomainService, IChatFeatureChecker
    {
        private readonly IFeatureChecker _featureChecker;

        public ChatFeatureChecker(
            IFeatureChecker featureChecker
        )
        {
            _featureChecker = featureChecker;
        }

        public void CheckChatFeatures(Guid? sourceTenantId, Guid? targetTenantId)
        {
            CheckChatFeaturesInternal(sourceTenantId, targetTenantId, ChatSide.Sender);
            CheckChatFeaturesInternal(targetTenantId, sourceTenantId, ChatSide.Receiver);
        }

        private async void CheckChatFeaturesInternal(Guid? sourceTenantId, Guid? targetTenantId, ChatSide side)
        {
            var localizationPosfix = side == ChatSide.Sender ? "ForSender" : "ForReceiver";
            if (sourceTenantId.HasValue)
            {
                if (!await _featureChecker.IsEnabledAsync(AppFeatures.ChatFeature))
                {
                    throw new UserFriendlyException(("ChatFeatureIsNotEnabled" + localizationPosfix));
                }

                if (targetTenantId.HasValue)
                {
                    if (sourceTenantId == targetTenantId)
                    {
                        return;
                    }

                    if (!await _featureChecker.IsEnabledAsync(AppFeatures.TenantToTenantChatFeature))
                    {
                        throw new UserFriendlyException(("TenantToTenantChatFeatureIsNotEnabled" + localizationPosfix));
                    }
                }
                else
                {
                    if (!await _featureChecker.IsEnabledAsync(AppFeatures.TenantToHostChatFeature))
                    {
                        throw new UserFriendlyException(("TenantToHostChatFeatureIsNotEnabled" + localizationPosfix));
                    }
                }
            }
            else
            {
                if (targetTenantId.HasValue)
                {
                    //targetTenantId.Value, 
                    if (!await _featureChecker.IsEnabledAsync(AppFeatures.TenantToHostChatFeature))
                    {
                        throw new UserFriendlyException(("TenantToHostChatFeatureIsNotEnabled" + (side == ChatSide.Sender ? "ForReceiver" : "ForSender")));
                    }
                }
            }
        }
    }
}